<?php

class Status_Object_TagsCounter {
  
  /* 
	definition of the tagscounter  table 
	this table contains the number of times each tag is used by people
  */  

  static protected $_dbTagsCounterTableName = 'tagscounter';
  static protected $_dbTagsCounterTagCol = 'tag';
  static protected $_dbTagsCounterCounterCol = 'count';
  
  
  /* need to put a limit to the number of pages that can be retrieved */
  static protected $_limitPage = 1000;
  
  static protected $_allowedWhereCondition = array('begin','end','anywhere');
  
     /*
	__construct - public constructor of the class. It is defined by the type of timeline that is requested and the identifier of the timeline
	*/
  public function __construct() {}	//end constructor


  //This function publish the status to the different tags counter
  //Only public statuses are published to the tags counter
  //This feature is usefull to present relevant tags while the user is typing
  
  static public function publishStatus($oStatus) {

	//basic data check
	if(!($oStatus instanceof Status_Object_Status)) {
		require_once('status/objects/Exception.php');
		throw new Status_Object_Exception('invalid status',60);
	}
	
	$isPrivate = $oStatus->isPrivate();
	if($isPrivate) return;

	//We retrieve the list of tags
	$tags = $oStatus->getTags();
	if(empty($tags)) return;
	
	//we get the tag counter database
	$db = self::_getTagsCounterDbStatic();
	foreach($tags as $num => $tag) {
		//we count the current amount of tags
		$select = $db->select()->from(self::$_dbTagsCounterTableName)->where($db->quoteInto(self::$_dbTagsCounterTagCol.' = ?',$tag));
		$res = $db->fetchAll($select->__toString());    	  


		//if the tag doesn t exists we create it
		if(empty($res)) {
			$db->insert(self::$_dbTagsCounterTableName,array(self::$_dbTagsCounterTagCol => $tag, self::$_dbTagsCounterCounterCol => 1));
		} else {
		//if the tag exists, we increment the tag number and saves it
			$newValue = $res[0][self::$_dbTagsCounterCounterCol] +1;
			$db->update(self::$_dbTagsCounterTableName,array(self::$_dbTagsCounterCounterCol => $newValue),$db->quoteInto(self::$_dbTagsCounterTagCol.' = ?',$tag));
		} //end else tag exists
		
	} //end foreach tag	


  } //end publishStatus
	
  
  
  
    //This function delete the status from the different tags counter
  //Only public statuses are published to the tags counter
  //This feature is usefull to present relevant tags while the user is typing
  
  static public function deleteStatus($oStatus) {

	//basic data check
	if(!($oStatus instanceof Status_Object_Status)) {
		require_once('status/objects/Exception.php');
		throw new Status_Object_Exception('invalid status',60);
	}
	
	$isPrivate = $oStatus->isPrivate();
	if($isPrivate) return;

	//We retrieve the list of tags
	$tags = $oStatus->getTags();
	if(empty($tags)) return;
	
	//we get the tag counter database
	$db = self::_getTagsCounterDbStatic();
	foreach($tags as $num => $tag) {
		//we count the current amount of tags
		$select = $db->select()->from(self::$_dbTagsCounterTableName)->where($db->quoteInto(self::$_dbTagsCounterTagCol.' = ?',$tag));
		$res = $db->fetchAll($select->__toString());    	  


		//if the tag doesn t exists we create it
		if(empty($res)) {
			continue;
		} else {
		//if the tag exists, we increment the tag number and saves it
			$newValue = $res[0][self::$_dbTagsCounterCounterCol] -1;
			if($newValue == 0) $db->delete(self::$_dbTagsCounterTableName,$db->quoteInto(self::$_dbTagsCounterTagCol.' = ?',$tag));
			else $db->update(self::$_dbTagsCounterTableName,array(self::$_dbTagsCounterCounterCol => $newValue),$db->quoteInto(self::$_dbTagsCounterTagCol.' = ?',$tag));
		} //end else tag exists
		
	} //end foreach tag	


  } //end deleteStatus
  
  
  
  
  
  
  //Object model when returned in the API
  public function asArray() {

  } //end asArray
  


	static public function formatPage($page = 1) {
		if(empty($page)) $page = 1;
		$validator = new Zend_Validate_Digits();
		if(!$validator->isValid($page)) {
			require_once('status/objects/Exception.php');
			throw new Status_Object_Exception('invalid input parameters',15);      	
		}
		if(self::$_limitPage < $page) {
			require_once('status/objects/Exception.php');
			throw new Status_Object_Exception('page search is limited to '.self::$_limitPage.' pages',15);   	  	
		}

		if($page < 1 ) $page = 1;
		return $page;		
	} //end formatPage

	static public function formatPerPage($perPage = 20) {
		if(empty($perPage)) $perPage = 20;
		$validator = new Zend_Validate_Digits();
		if(!$validator->isValid($perPage)) {
		require_once('status/objects/Exception.php');
		throw new Status_Object_Exception('invalid input parameters',15);      	
		}
		if($perPage < 1 ) $perPage = 1;
		if($perPage > 100 ) $perPage = 100;
		return $perPage;
	} //end formatPerPage
  
  
  
  
  
	static public function listing($pattern,$where,$perPage,$page) {
		if(empty($pattern)) {
			require_once('status/objects/Exception.php');
			throw new Status_Object_Exception('Pattern is empty',44);      	
		}	  
		if(!self::_isValidTag($pattern)){
			require_once('status/objects/Exception.php');
			throw new Status_Object_Exception('Pattern is invalid',46); 		
		}
		
		if(empty($where)) $where = 'begin';
		
		if(!in_array($where,self::$_allowedWhereCondition)) {
			require_once('status/objects/Exception.php');
			throw new Status_Object_Exception('Where condition is not an allowed one',45);  		
		}
		  
		$page = self::formatPage($page);
		$perPage = self::formatPerPage($perPage);  
		
		//we get the database and generate the where condition
		$db = self::_getTagsCounterDbStatic();
		$select = $db->select()->from(self::$_dbTagsCounterTableName)->limitPage($page, $perPage);
		
		//where condition depends on the where parameter
		if($where == 'begin') $select->where($db->quoteInto(self::$_dbTagsCounterTagCol.' LIKE ?',$pattern.'%'));
		elseif($where == 'end') $select->where($db->quoteInto(self::$_dbTagsCounterTagCol.' LIKE ?','%'.$pattern));
		elseif($where == 'anywhere') $select->where($db->quoteInto(self::$_dbTagsCounterTagCol.' LIKE ?','%'.$pattern.'%'));
		
		$select->order(self::$_dbTagsCounterCounterCol.' DESC');
		
		$res = $db->fetchAll($select->__toString());

		return $res;
		
	
	} //end listing
  
  

   static protected function _getTagsCounterDbStatic() {
		return Zend_Registry::get('dt_dbs')->getDb('status','tagsCounter','key');	
  } //end _getTagsCounterDbStatic

  
  static protected function _isValidTag($tag) {
   	if(preg_match(  '/([^a-zA-z0-9_]+)/i'  ,  $tag)) return false;
	return true;
  } //end _isValidTag

  
  
} //end class